<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>3.代理模式典型应用之虚拟代理（图片预加载）</title>
</head>
 <style>
     #background{
         width: 600px;
         height: 550px;
     }
     #background img{
         width: 100%;
         height: 100%;
     }
     button{
         width: 80px;
         height: 60px;
     }
 </style>
<body>
    <div id="btnWrap">
        <Button data-src="/images/image1.jpeg">1</Button>
        <Button data-src="/images/image2.jpeg">2</Button>
        <Button data-src="/images/image3.jpeg">3</Button>
    </div>
    <div id="background">
        <img src="/images/image6.jpeg" alt="" id= 'bg-img'>
    </div>

    <script>
        // 设置背景的类
        class Background{
            constructor(){
                this.background = document.getElementById('bg-img');
                console.log(3);
            };
            setSrc(src){
                this.background.src = src;
                console.log(4,src);
            }
        };
        //代理类
        class LoadingBackground{
           static LOADING_URL = '/getLoading';
            constructor(){
                this.Background = new Background();
                console.log(2);
            };
            setSrc(src){
                this.Background.setSrc(LoadingBackground.LOADING_URL);
                let img = new Image();
                img.src = src;
                let that = this;
                img.onload = function () { 
                    that.Background.setSrc(src);
                 };
                console.log(5);
            }
        };

        document.getElementById('btnWrap').addEventListener('click',e=>{
            console.log(e.target.dataset.src);
            let currentSrc = e.target.dataset.src;
            if(currentSrc){
                console.log(1);
                let BgInstance = new LoadingBackground();
                BgInstance.setSrc (currentSrc);
            }
        })

    </script>
</body>
</html>
